package com.example.apple.paopo.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.apple.paopo.PAOPOinterface.PaoPointerface;
import com.example.apple.paopo.R;
import com.example.apple.paopo.base.BaseActivity;
import com.example.apple.paopo.dialog.PaoPoDialog;
import com.orhanobut.logger.Logger;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxRegTool;
import com.vondear.rxtools.view.RxToast;
import com.zyao89.view.zloading.ZLoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import cn.bmob.v3.AsyncCustomEndpoints;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CloudCodeListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by apple on 17/12/1.
 */

@ContentView(R.layout.activity_registered)
public class RegisteredActivity extends BaseActivity {
    @ViewInject(R.id.tool_title)
    TextView toolText;
    @ViewInject(R.id.tool_more)
    ImageView toolMore;
    @ViewInject(R.id.et_registered_phone)
    EditText phone;
    @ViewInject(R.id.et_registered_email)
    EditText email;
    @ViewInject(R.id.et_registered_pwd1)
    EditText pwd1;
    @ViewInject(R.id.et_registered_pwd2)
    EditText pwd2;
    @ViewInject(R.id.et_registered_inviter)
    EditText inviter;//邀请人
    @ViewInject(R.id.et_registered_verification)
    EditText verification;
    @ViewInject(R.id.et_registered_userName)
    EditText userName;
    @ViewInject(R.id.tv_registered_countdown)
    TextView countdown;
    @ViewInject(R.id.et_registered_verificationsend)
    Button verificationsend;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        toolMore.setVisibility(View.GONE);
        toolText.setText("注册界面");
//       // BmobSMS.initialize(context, "", new MySMSCodeListener());
      //  BmobSMS.initialize(context,Bmob_Application_ID,new MySMSCodeListener());
    }

    //返回方法
    @Event(R.id.tool_break)
    private void ToolbreakAction(View v){
        finish();
    }

    //验证码发送
    @Event(R.id.et_registered_verificationsend)
    private void verificationSendAction(View v){
        if(!RxNetTool.isNetworkAvailable(this)){
            RxToast.error(this,"发送失败，请检查网络是否可用").show();
        }else if(!RxRegTool.isMobileExact(phone.getText().toString())){
            RxToast.error(this,"该手机号码不正确,请重新输入").show();
        }else{

            isPhone(phone.getText().toString(), new PaoPointerface() {
                @Override
                public void isPhone(Boolean bool){
                    if (!bool){
                        BmobSMS.requestSMSCode(phone.getText().toString(),"注册模版", new QueryListener<Integer>() {
                            @Override
                            public void done(Integer integer, BmobException e) {
                                if(e==null){//验证码发送成功
                                    RxToast.normal(RegisteredActivity.this,"验证码已经发送，请注意查收").show();
                                    Logger.d("bmob", "短信id："+integer);//用于查询本次短信发送详情
                                    //RxTool.countDown(countdown,120,1,"");

                                    countdown.setEnabled(false);
                                    verificationsend.setEnabled(false);
                                    final CountDownTimer timer = new CountDownTimer(120*1000,1000) {
                                        public void onTick(long millisUntilFinished) {
                                            countdown.setText(millisUntilFinished / 1000L + " S");
                                        }

                                        public void onFinish() {
                                            countdown.setText("");
                                            countdown.setEnabled(true);
                                            verificationsend.setEnabled(true);
                                        }
                                    };
                                    timer.start();

                                }else {
                                    verificationsend.setEnabled(true);
                                    Logger.d(e.toString());
                                    if (e.getErrorCode()==10010){
                                        RxToast.error(RegisteredActivity.this,"该手机号码今日获取短信过多，请明天在获取").show();
                                    }else {
                                        RxToast.error(RegisteredActivity.this, "验证码发送失败，请重新发送").show();
                                    }
                                }
                            }
                        });

                    }else {
                        RxToast.info(RegisteredActivity.this,"该号码已经注册，请更换号码").show();
                    }
                }

                @Override
                public void isEmail(Boolean bool) {

                }
            });
        }
//        BmobSMS.requestSMS(phone.getText().toString(),,null,)
        //BmobSMS.requestSMS(this, phone.getText().toString(),verification.getText().toString(),null,new QueryListener<>())
    }
    //判断邮箱是否注册
    private void isEmail(String isemail , final PaoPointerface paopo){
        RequestParams params = new RequestParams("http://cloud.bmob.cn/91c9d2dffacfcd37/isEmail");
        params.addQueryStringParameter("email",isemail);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Boolean flog = true;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.getString("Sate").equals("YES")) {
                        flog = true;
                    } else {
                        flog = false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                paopo.isEmail(flog);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Boolean flog = true;
                paopo.isEmail(flog);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
//       // isEmail
//        AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
//        //第一个参数是云函数的方法名称，
//        // 第二个参数是上传到云函数的参数列表（JSONObject cloudCodeParams），
//        // 第三个参数是回调类
//        JSONObject params = new JSONObject();
//
//        try {
//            params.put("email",isemail);
//        } catch (JSONException e1) {
//            e1.printStackTrace();
//        }
//
//        ace.callEndpoint("isEmail", params, new CloudCodeListener() {
//            @Override
//            public void done(Object object, BmobException e) {
//                Boolean flog=true;
//                if (e == null) {
//                    JSONObject json = (JSONObject) object;
//                    try {
//                        if (json.getString("Sate").equals("YES")){
//                            flog=true;
//                        }else {
//                            flog =false;
//                        }
//                    } catch (JSONException e1) {
//                        e1.printStackTrace();
//                    }
//                } else {
//                    flog = true;
//                    Logger.d(e.getMessage());
//
//                }
//                paopo.isEmail(flog);
//            }
//        });
    }

    //判断手机号码是否注册
    private void isPhone(String isphone, final PaoPointerface paopo){
        // isEmail
        AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
        //第一个参数是云函数的方法名称，
        // 第二个参数是上传到云函数的参数列表（JSONObject cloudCodeParams），
        // 第三个参数是回调类
        JSONObject params = new JSONObject();

        try {
            params.put("phone",isphone);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        ace.callEndpoint("isPhone", params, new CloudCodeListener() {
            @Override
            public void done(Object object, BmobException e) {
                Boolean flog =true;
                if (e == null) {
                    JSONObject json = null;
                    try {
                        json = new JSONObject(object.toString());
                        if (json.getString("sate").equals("YES")){
                            flog=true;
                        }else {
                            flog =false;
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                } else {
                    flog = true;
                    Logger.d(e.getMessage().toString());

                }
                paopo.isPhone(flog);
            }
        });
    }

    //确认注册
    @Event(R.id.et_registered_confirm)
    private void confirmSubmitAction(View v){
        if(!RxNetTool.isNetworkAvailable(this)){
            RxToast.error(this,"注册失败，请检查网络是否可用").show();
        }else if (!RxRegTool.isMobileExact(phone.getText().toString())){
            RxToast.info(this,"手机号不正确，请重新输入").show();
        }else if (!RxRegTool.isEmail(email.getText().toString())){
            RxToast.info(this,"邮箱不正确，请重新输入").show();
        }else if (pwd1.getText().length()==0||pwd2.getText().length()==0){
            RxToast.info(this,"密码不能为空，请重新输入").show();
        }else if (verification.getText().length()==0){
            RxToast.info(this,"验证码不能为空，请重新输入").show();
        }else if (userName.getText().length()==0){
            RxToast.info(this,"账号不能为空，请重新输入").show();
        } else {
            final ZLoadingDialog dialog = PaoPoDialog.getPaoPoDialog(RegisteredActivity.this,"正在注册中,请稍后...");
            isEmail(email.getText().toString(), new PaoPointerface() {
                @Override
                public void isPhone(Boolean bool) {

                }

                @Override
                public void isEmail(Boolean bool) {
                    if (!bool){
                        Logger.d("手机号码:"+phone.getText().toString()+"验证码:"+verification.getText().toString());
                        BmobSMS.verifySmsCode(phone.getText().toString(), verification.getText().toString(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                // TODO Auto-generated method stub
                                if(e==null){//短信验证码已验证成功
                                    Logger.d("bmob", "验证通过");


                                    AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
                                    //第一个参数是云函数的方法名称，
                                    // 第二个参数是上传到云函数的参数列表（JSONObject cloudCodeParams），
                                    // 第三个参数是回调类
                                    JSONObject params = new JSONObject();

                                    try {
                                        params.put("phone",phone.getText().toString());
                                        params.put("email",email.getText().toString());
                                        params.put("pwd",pwd1.getText().toString());
                                        params.put("inviter",inviter.getText().toString());
                                        params.put("user",userName.getText().toString());
                                    } catch (JSONException e1) {
                                        e1.printStackTrace();
                                    }

                                    ace.callEndpoint("registeredUserAction", params, new CloudCodeListener() {
                                        @Override
                                        public void done(Object object, BmobException e) {
                                            if (e == null) {
                                                Logger.d(object.toString());
                                                try {
                                                    JSONObject json =new JSONObject(object.toString());
                                                    if (json.getString("state").equals("YES")){
                                                        RxToast.success("注册成功");
                                                        finish();
                                                    }else {
                                                        RxToast.normal("注册失败，"+json.getString("msge"));
                                                    }
                                                } catch (JSONException e1) {
                                                    e1.printStackTrace();
                                                }
                                            } else {
//                    Log.e(TAG, " " + e.getMessage());
                                                Logger.d(e.getMessage());

                                            }
                                        }
                                    });



                                }else{
                                    switch (e.getErrorCode()){
                                        case 207:
                                            RxToast.error("验证码错误，请重新输入");
                                            break;
                                    }
                                    Logger.d("bmob", "验证失败：code ="+e.getErrorCode()+",msg = "+e.getLocalizedMessage());
                                }
                            }
                        });
                        dialog.dismiss();

                    }else {

                        RxToast.error("邮箱已被注册，请更换邮箱");
                        dialog.dismiss();
                    }
                }
            });
        }
    }

}
